package com.jack.leetcode.eachProblem07;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zhang_j on 2020/7/13
 */
public class 两个数组的交集2 {

    public static void main(String[] args) {
        int[] a = {4,9,5};
        int[] b = {9,4,9,8,4};
        int[] intersect = intersect(a, b);
        for (int i : intersect) {
            System.out.print(i + ",");
        }
    }

    public static int[] intersect(int[] nums1, int[] nums2) {
        if(nums1 == null || nums2 == null){
            return null;
        }
        int m = nums1.length;
        int n = nums2.length;
        if(m < n){
            return intersect(nums2, nums1);
        }
        List<Integer> first = Arrays.stream(nums1).boxed().collect(Collectors.toList());
        List<Integer> second = Arrays.stream(nums2).boxed().collect(Collectors.toList());
        List<Integer> result = new ArrayList<>();

        Iterator<Integer> iterator = second.iterator();
        while(iterator.hasNext()){
            Integer next = iterator.next();
            if(first.contains(next)){
                result.add(next);
                first.remove(next);
            }
        }

        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}
